const util = require('util');
const fs = require('fs');
const readFile = util.promisify(fs.readFile);

class template {
    constructor(filePath) {
        this.filePath = filePath;
    }

    async parse(data) {
        const tpl = await readFile(this.filePath);
        const str = tpl.toString();
        const re = /<%|%>/g;
        let fixIndex = 0;
        let outStr = 'view = `';
        let start = 0;
        while (true) {
            const m = re.exec(str);
            if (m == null) {
                if (start == 0) {
                    outStr += str;
                }
                break;
            }

            const pos = m.index;
            if (pos > start) {
                outStr += str.substring(start, pos);
                start = pos + 2;
            }

            if (fixIndex % 2 != 0) {
                outStr += 'view +=`';
            } else {
                outStr += '`;';
            }
            fixIndex++;
        }
        if (fixIndex % 2 == 0) {
            outStr += '`;';
        }
        outStr += 'return view;';
        return new Function('_', outStr)(data);
    }
}

module.exports = template;